﻿using IOT4Week1Day1.App.Dtos;
using IOT4Week1Day1.Domain.IRepositories;
using IOT4Week1Day1.Domain.Models;
using System.Collections.Generic;
using System.Linq;

namespace IOT4Week1Day1.App
{
    /// <summary>
    /// 用户模块的功能，全部放在UserAppService里面写
    /// </summary>
    public class UserAppService : IUserAppService
    {
        private readonly IUserRepository _userRepository;

        public UserAppService(IUserRepository repository)
        {
            _userRepository = repository;
        }

        /// <summary>
        /// 查询是否有这个用户，如果有，则返回此用户信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public User Login(LoginDto input)
        {
            //查询数据，看看用户是否存在
            User user = _userRepository.GetTable()
                                       .Where(x => x.UserName.Equals(input.Name) && x.Password.Equals(input.Pass))
                                       .SingleOrDefault();

            //bool re = _userRepository.GetTable()
            //                           .Any(x => x.UserName.Equals(input.Name) && x.Password.Equals(input.Pass));

            return user;
        }

        /// <summary>
        /// 逻辑删除功能（批量修改状态）
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public int Delete(string ids)
        {
            //把ids拆分成一个数组
            string[] arr = ids.Split(',');
            foreach (var id in arr)
            {
                int i = int.Parse(id);
                User u = _userRepository.Get(i); //根据主键获取数据
                if (u != null)
                {
                    u.IsDeleted = true;  //修改状态
                    _userRepository.Update(u);
                }
            }

            return _userRepository.Save();  //保存修改

        }

        /// <summary>
        /// 分页
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public PagedList<User> GetPage(int pageIndex, int pageSize, string name, bool? status)
        {
            var tuple = _userRepository.GetPage(pageIndex, pageSize, name, status);

            return new PagedList<User>() { TotalCount=tuple.total, PagedData= tuple.list };
        }


        /// <summary>
        /// 返填
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public User Get(int id)
        {
            return _userRepository.Get(id);
        }

        /// <summary>
        /// 修改功能
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public int UpdateUser(User input)
        {
            _userRepository.Update(input);
            return _userRepository.Save();  //最后要保存，否则不会影响数据库
        }

    }
}
